package com.xingkeduo.controller.base;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.util.CollectionUtils;

import com.xingkeduo.model.param.ActivityDaysParam;
import com.xingkeduo.model.param.ActivityParam;
import com.xingkeduo.model.param.ActivityParam.ActivityModeEnum;
import com.xingkeduo.model.param.ActivityParam.ActivityTypeEnum;
import com.xingkeduo.model.param.ActivityParam.PreferentialModeEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingServiceTypeEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingTypeEnum;
import com.xingkeduo.model.param.common.BaseParam;
import com.xingkeduo.util.StringUtils;
import com.xingkeduo.util.pojo.exception.DataException;
import com.xingkeduo.util.tool.ResponseMessage;

public class ActivityBaseController extends InitController {
	protected void initParams(BaseParam baseParam) {
		super.initUserInParams(baseParam);
		ResponseMessage checkResult = checkRequestParam(baseParam);
		if (checkResult.getStatus() != ResponseMessage.ok().getStatus()) {
			throw new DataException(DataException.Type.FAIL, checkResult.getMsg());
		}
	}
	protected ResponseMessage checkRequestParam(BaseParam baseParam) {
		ActivityParam activityTemplate = (ActivityParam) baseParam;
		if (activityTemplate.getActivityType() == null) {
			return ResponseMessage.error("缺少活动类型(支付活动/代购活动/分流活动)", 500);
		}
		String activityType = ActivityTypeEnum.parse(activityTemplate.getActivityType()).getDesc();
		if (activityTemplate.getActivityMode() == null) {
			return ResponseMessage.error("缺少活动类型(门店活动/发型师活动)", 500);
		}
		if (activityTemplate.getPreferentialMode() == null) {
			return ResponseMessage.error(activityType + "优惠方式缺失", 500);
		}
		if (StringUtils.isBlank(activityTemplate.getName())) {
			return ResponseMessage.error(activityType + "名称缺失", 500);
		}
		if (activityTemplate.getLeastCost() == null) {
			activityTemplate.setLeastCost(BigDecimal.valueOf(0));
		}
		if (activityTemplate.getLeastCost().compareTo(BigDecimal.valueOf(0)) < 0
				|| activityTemplate.getLeastCost().compareTo(BigDecimal.valueOf(100000)) > 0) {
			return ResponseMessage.error("使用门槛范围0.01～100000", 500);
		}
		if ((!activityTemplate.getActivityType().equals(ActivityTypeEnum.HELP_PAYMENT.getStatusType()))
				&& StringUtils.isBlank(activityTemplate.getSupportServprodIds())) {
			activityTemplate.setSupportServprodIds("0");
			activityTemplate.setSupportServprodNames("支持所有服务");
		}
		if (activityTemplate.getActivityAmount() == null) {
			activityTemplate.setActivityAmount(BigDecimal.valueOf(0));
		}
		if (activityTemplate.getActivityAmount().compareTo(BigDecimal.valueOf(0)) < 0) {
			return ResponseMessage.error(activityType + "面额小于0", 500);
		}
		if (activityTemplate.getPreferentialMode().equals(PreferentialModeEnum.DISCOUNT.getCode())
				&& activityTemplate.getActivityAmount().compareTo(BigDecimal.valueOf(10)) > 0) {
			return ResponseMessage.error("折扣面额超过10折", 500);
		}
		if (activityTemplate.getPreferentialMode().equals(PreferentialModeEnum.DISCOUNT.getCode())) {
			activityTemplate.setActivityAmount(activityTemplate.getActivityAmount().divide(BigDecimal.valueOf(10), 2, BigDecimal.ROUND_HALF_DOWN));
		}
		if (activityTemplate.getStockQuantity() == null) {
			activityTemplate.setStockQuantity(0);
		}
		if (activityTemplate.getStockQuantity() == null || activityTemplate.getStockQuantity().intValue() < 0
				|| activityTemplate.getStockQuantity().intValue() > 10000000) {
			return ResponseMessage.error("库存范围为1～10,000,000张", 500);
		}
		if (activityTemplate.getUseLimitDay() == null) {
			activityTemplate.setUseLimitDay(0);
		}
		if (activityTemplate.getUseLimitDay().intValue() < 0 || activityTemplate.getUseLimitDay().intValue() > 1000) {
			return ResponseMessage.error("单日参与范围为1～1000次", 500);
		}
		if (activityTemplate.getUseLimitTotal() == null) {
			activityTemplate.setUseLimitTotal(0);
		}
		if (activityTemplate.getUseLimitTotal().intValue() < 0
				|| activityTemplate.getUseLimitTotal().intValue() > 1000) {
			return ResponseMessage.error("累积参与范围为1～1000次", 500);
		}
		if (StringUtils.isBlank(activityTemplate.getStoreIds())) {
			activityTemplate.setStoreIds("0");
			activityTemplate.setStoreNames("适用所有门店");
		}
		if (StringUtils.isBlank(activityTemplate.getWeekHourIds())) {
			activityTemplate.setWeekHourIds("0");
		}
		if (activityTemplate.getIsOverlying() == null) {
			activityTemplate.setIsOverlying(0);
		}
		if (activityTemplate.getPreferentialMode().equals(PreferentialModeEnum.SPECIAL_OFFER.getCode())
				|| activityTemplate.getPreferentialMode().equals(PreferentialModeEnum.FREE.getCode())) {
			activityTemplate.setIsOverlying(0);
		}
		if (activityTemplate.getIsOverlying().intValue() == 1
				&& (activityTemplate.getPreferentialMode().equals(PreferentialModeEnum.SPECIAL_OFFER.getCode())
						|| activityTemplate.getPreferentialMode().equals(PreferentialModeEnum.FREE.getCode()))) {
			return ResponseMessage.error("特价不能选择与优惠券同享", 500);
		}
		if (activityTemplate.getActivityMode().equals(ActivityModeEnum.HAIRDRESSER.getCode())
				&& activityTemplate.getHairStyleId() == null) {
			return ResponseMessage.error("缺少服务发型师", 500);
		}
		String storeIds = com.xingkeduo.util.BeanUtils.buildStartAndEndWithZero(activityTemplate.getStoreIds());
		activityTemplate.setStoreIds(storeIds);
		String supportServprodIds = com.xingkeduo.util.BeanUtils
				.buildStartAndEndWithZero(activityTemplate.getSupportServprodIds());
		activityTemplate.setSupportServprodIds(supportServprodIds);
		String daysIds = buildDaysStartAndEndWithZero(activityTemplate.getActivityType(),activityTemplate.getActivityDaysParams());
		activityTemplate.setWeekHourIds(daysIds);
		if(activityTemplate.getStartTime() != null 
				&& activityTemplate.getEndTime() != null
				&& activityTemplate.getStartTime().after(activityTemplate.getEndTime())) {
			return ResponseMessage.error("活动开始时间不能大于结束时间", 500);
		}
		return checkDaysTimeCross(activityTemplate.getActivityDaysParams());
	}

	public String buildDaysStartAndEndWithZero(String activityType,List<ActivityDaysParam> activityDaysParams) {
		String str = "0";
		if (activityType.equalsIgnoreCase(ActivityTypeEnum.BYPASS_FLOW.getStatusType()) 
				&& CollectionUtils.isEmpty(activityDaysParams)) {
			throw new RuntimeException("请选择优惠时间段");
			//return str;
		}else if (CollectionUtils.isEmpty(activityDaysParams)){
			return str;
		}
		StringBuffer dayIdsBuffer = new StringBuffer();
		for (int i = 0; i < activityDaysParams.size(); i++) {
			ActivityDaysParam days = activityDaysParams.get(i);
			if (StringUtils.isBlank(days.getDayids()) 
					|| days.getStartTime() == null 
					|| days.getStartTime() == null) {
				throw new RuntimeException("请选择优惠时间段");
			}
			if (days.getStartTime().after(days.getEndTime())) {
				throw new RuntimeException("优惠开始时间必须小于结束时间");
			}
			if(activityType.equalsIgnoreCase(ActivityTypeEnum.BYPASS_FLOW.getStatusType()) 
					&& (days.getActivityAmount() == null 
						|| days.getActivityAmount().compareTo(BigDecimal.valueOf(0))<0)) {
				throw new RuntimeException("请填写优惠金额");
			}
			String daysStr = days.getDayids().replaceAll(",,", ",");
			if (daysStr.startsWith(",")) {
				daysStr = daysStr.substring(1, daysStr.length());
			}
			if (daysStr.endsWith(",")) {
				daysStr = daysStr.substring(0, daysStr.length() - 1);
			}
			days.setDayids(daysStr);
			dayIdsBuffer.append(daysStr).append(",");
		}
		str = com.xingkeduo.util.BeanUtils.removerepeatedchar(dayIdsBuffer.toString()).replaceAll(",,", ",");
		if (str.endsWith(",")) {
			str = str.substring(0, str.length() - 1);
		}
		return str;
	}

	protected ResponseMessage checkDaysTimeCross(List<ActivityDaysParam> activityDaysParams) {
		// 校验可参与时间是否有交叉 思路：当数据条数大于1时，进行校验
		if(activityDaysParams!=null&&activityDaysParams.size()>1)
		{
			for (int i = 0; i < activityDaysParams.size() - 1; i++) {
				Map<String, Boolean> dayMap = new HashMap<>();// 保存当前一行数据中的days
				Date startDate = activityDaysParams.get(i).getStartTime();
				Date endDate = activityDaysParams.get(i).getEndTime();
				String days = activityDaysParams.get(i).getDayids();
				String[] daysArr = days.split(",");// 假设选中的周天有值 需判空处理？
				for (int x = 0; x < daysArr.length; x++) {
					dayMap.put(daysArr[x], true);
				}
				for (int j = i + 1; j < activityDaysParams.size(); j++) {
					Date startDate1 = activityDaysParams.get(j).getStartTime();
					Date endDate1 = activityDaysParams.get(j).getEndTime();
					String days1 = activityDaysParams.get(j).getDayids();
					// 假设选中的周天有值 需判空处理？
					String[] daysArr1 = days1.split(",");
					for (int x = 0; x < daysArr1.length; x++) {
						if (dayMap != null && dayMap.get(daysArr1[x]) != null && dayMap.get(daysArr1[x])) {// 对比时间是否交叉
							if ((startDate.before(startDate1) && endDate.after(startDate1))
									|| (startDate.before(endDate1) && endDate.after(endDate1))
									|| (startDate1.before(startDate) && endDate1.after(startDate))
									|| (startDate1.before(endDate) && endDate1.after(endDate))
									|| startDate.equals(startDate1) || startDate.equals(endDate1)
									|| endDate.equals(startDate1) || endDate.equals(endDate1)) {
//										System.out.println("第"+i+"条数据与第"+j+"条数据时间交叉了 day:" +daysArr1[x] );
								return ResponseMessage.error("参与时间不能重叠！", 500);
							}
						}
					}
				}
			}
		}
		return ResponseMessage.ok();
	}
}
